let config = require("./config");
/* -------------------------------------------------------------------------- */
let destination = config.destination;
if (config.remoteUpdate) {
  log("getDownloadLink");
  let url = getDownloadLink();
  log("downloadFile");
  let downloadFilePath = downloadFile(url);
  log("decompressFile");
  decompressFile(downloadFilePath, destination);
  log("entrance: cwd: " + files.cwd());
  copyFile(destination, files.cwd());
}
function copyFile(dir, destination) {
  files.listDir(dir).map((file) => {
    let src = dir + file;
    let dest = destination + "/" + file;
    log("src: " + src);
    log("dest: " + dest);
    files.copy(src, dest);
  });
}

// engines.execScriptFile(destination + "main.js", {
//   path: config.destination,
// });
// 由于要使用node_module, 因此只能用app本身内置的路径
engines.execScriptFile(files.cwd() + "/main.js");
log("启动完成: main.js");
/* -------------------------------------------------------------------------- */

function decompressFile(src, destination) {
  $files.remove(destination);
  files.createWithDirs(destination);
  $zip.unzip(src, destination);
}
function getDownloadLink() {
  let remoteUrl = "https://www.yuque.com/yashujs/di90k3/gp5w5cmfqd76pfy1";
  let r = http.get(remoteUrl, {
    headers: {
      authority: "<authority>",
      cookie: "<cookie>",
      "sec-fetch-user": "<sec-fetch-user>",
      "upgrade-insecure-requests": "<upgrade-insecure-requests>",
      "User-Agent": "apifox/1.0.0 (https://www.apifox.cn)",
    },
  });
  let data = r.body.string();
  let filterData = data.match(/-{9}.+?-{9}/)[0];
  filterData = filterData.replace(/-{9}/g, "");
  filterData = decodeURIComponent(filterData);
  return filterData;
}
function downloadFile(url) {
  // let url = "192.168.5.22:3001/download";
  let r = http.post(url, {
    headers: {
      "Content-Type": "application/json",
    },
    fileName: "build.zip",
  });
  let data = r.body;
  // log(data);
  let filePath = config.downloadFilePath;
  files.createWithDirs(filePath);
  files.writeBytes(filePath, data.bytes());
  return filePath;
}
